<?php
namespace app\common\logic;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use think\facade\Config;

class RabbitMQ extends Base{
    
    /**
     * @desc 配置文件
     * @var array
     */
    protected $config = [];
    
    /**
     * @desc 连接对象
     * @var string
     */
    protected $connection = '';
    
    /**
     * @desc 初始化
     * rabbitMQ constructor.
     */
    public function __construct() {
        $this->config = Config::pull('rabbitmq');
    }
    
    /**
     * @param int $type 信息类型
     * @param string $msg json字符消息
     * @return bool
     */
    public function send($type, $msg = '') {
        $queueName = $this->config['channel']['centOs'][$type];
        if (!$queueName || !$msg) {
            return false;
        }
        
        $connection = new AMQPStreamConnection($this->config['host'], $this->config['port'], $this->config['user'], $this->config['password']);
        $channel    = $connection->channel();
        $channel->queue_declare($queueName, false, false, false, false);
        
        //定义一个消息，消息内容为json字符串
        $body = new AMQPMessage($msg);
        $channel->basic_publish($body, '', $queueName);
        
        //关闭连接
        $channel->close();
        $connection->close();
        
        return true;
    }

    /**
     * @param int $queueName 队列名称
     * @param string $msg json字符消息
     * @return bool
     */
    public function sendByQueueName($queueName, $msg) {
        $connection = new AMQPStreamConnection($this->config['host'], $this->config['port'], $this->config['user'], $this->config['password']);
        $channel    = $connection->channel();
        $channel->queue_declare($queueName, false, false, false, false);

        //定义一个消息，消息内容为json字符串
        $body = new AMQPMessage($msg);
        $channel->basic_publish($body, '', $queueName);

        //关闭连接
        $channel->close();
        $connection->close();

        return true;
    }
}